/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2014 All Rights Reserved.
 */
package pay.biz;

import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import base.model.exception.BizHandleException;
import mt.Const;
import mt.model.enums.OrderStatusEnum;

/**
 * 交易状态变更通知
 * 
 * @author taixu.zqq
 * @version $Id: InAlipayOpenExecutor.java, v 0.1 2014年7月24日 下午5:05:13 taixu.zqq
 *          Exp $
 */
public class TradeNotifyAliExecutor implements TradeNotifyExecutor {

	private static final Logger LOG = Logger.getLogger(TradeNotifyAliExecutor.class);

	/*
	 * (non-Javadoc) @see
	 * com.unibroad.touchus.oss.biz.apay.executor.NotifyExecutor#execute(java.
	 * util.Map)
	 */
	@Override
	public synchronized void execute(Map<String, String> notifyDtMap) throws BizHandleException {

		if (notifyDtMap == null || notifyDtMap.isEmpty()) {
			throw new BizHandleException("订单状态通知处理异常,交易数据为空!");
		}

		// 获取本地订单
		String out_trade_no = notifyDtMap.get(Const.ALIPAY_MSG_OUT_TRADE_NO);
		Record order = Db.findFirst("select * from mt_order where orderId = ? for update", out_trade_no);
		if (order == null) {
			throw new BizHandleException("无法获取订单号!");
		}

		OrderStatusEnum orderStatus = OrderStatusEnum.getEnumByCode(order.getInt("status"));
		if (orderStatus == OrderStatusEnum.PAY_SUCCESS || orderStatus == OrderStatusEnum.TIMEOUT
				|| orderStatus == OrderStatusEnum.CANCEL || orderStatus == OrderStatusEnum.FINISHED) {
			return;
		}

		// 交易状态
		OrderStatusEnum targetSattus = orderStatus;
		ApayTradeStatusEnum tradeStatus = ApayTradeStatusEnum
				.getEnumByCode(notifyDtMap.get(Const.ALIPAY_MSG_TRADE_STATUS));
		switch (tradeStatus) {
		case FINISHED:
		case SUCCESS:
			targetSattus = OrderStatusEnum.PAY_SUCCESS;
			break;
		case CLOSED:
			targetSattus = OrderStatusEnum.TIMEOUT;
			break;
		case REFUND_SUCCESS:
			targetSattus = OrderStatusEnum.FUND_BACK;
			break;
		default:
			break;
		}

		// 修改订单状态
		boolean success = false;
		if (targetSattus != orderStatus) {
			order.set("updateTime", new Date());
			order.set("tradeNo", notifyDtMap.get("trade_no"));
			order.set("status", targetSattus.getCode());
			success = Db.update("mt_order", "orderId", order);
		}

		if (!success) {
			LOG.error("支付宝交易状态同步失败，out_trade_no = " + out_trade_no);
			throw new BizHandleException("支付宝交易状态同步失败，out_trade_no = " + out_trade_no);
		}

	}

}
